package com.getpebble.android.main.activity;

import android.app.ActionBar;
import android.app.AlertDialog.Builder;
import android.app.Fragment;
import android.app.FragmentManager.OnBackStackChangedListener;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.res.Configuration;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.Style;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.text.Layout.Alignment;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.TypedValue;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.getpebble.android.PebbleApplication;
import com.getpebble.android.R;
import com.getpebble.android.common.core.trace.Analytics.MobileAppBehavior;
import com.getpebble.android.common.core.trace.Analytics.Support;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.core.util.PblPreferences;
import com.getpebble.android.common.core.util.PblPreferences.PrefKey;
import com.getpebble.android.config.SyncBootConfig;
import com.getpebble.android.core.auth.activity.LoginActivity;
import com.getpebble.android.font.PblFont;
import com.getpebble.android.framework.PblFrameworkInterface;
import com.getpebble.android.framework.developer.PblDeviceObserver.ConnectedDeviceChangeListener;
import com.getpebble.android.main.drawer.fragment.DrawerFragment;
import com.getpebble.android.main.drawer.model.DrawerItem;
import com.getpebble.android.main.fragment.FragmentMetaData;
import com.getpebble.android.main.fragment.FragmentMetaData.FragmentData;
import com.getpebble.android.main.fragment.FragmentMetaData.FragmentType;
import com.getpebble.android.notifications.util.NotificationUtil;
import com.getpebble.android.onboarding.activity.OnboardingActivity;
import com.getpebble.android.onboarding.fragment.PebbleOnlyFragment;
import com.getpebble.android.util.BluetoothUtil;
import com.getpebble.android.util.DeepLink;
import com.getpebble.android.util.HttpUtils;
import com.getpebble.android.util.Sideloading;
import com.sun.mail.imap.protocol.ListInfo;
import com.sun.mail.smtp.SMTPMessage;
import java.util.concurrent.locks.ReentrantLock;

public class MainActivity extends TapToConnectActivity implements OnItemClickListener {
    private static final Handler sHandler = new Handler(Looper.getMainLooper());
    private int mActionBarColorId = R.color.actionbar_bg;
    private boolean mAllowNullStack = false;
    private ConnectedDeviceChangeListener mConnectedDeviceChangeListener = new ConnectedDeviceChangeListener() {
        public void notifyConnectedDeviceChanged() {
            MainActivity.this.runOnUiThread(new Runnable() {
                public void run() {
                    if (MainActivity.this.mIsResumed && MainActivity.this.runPrfLock.tryLock()) {
                        try {
                            MainActivity.this.runOnboardingIfNeeded();
                        } finally {
                            MainActivity.this.runPrfLock.unlock();
                        }
                    }
                }
            });
        }
    };
    private DrawerFragment mDrawerFragment = null;
    private DrawerLayout mDrawerLayout = null;
    private ActionBarDrawerToggle mDrawerToggle = null;
    private boolean mForceSkipOnboarding = false;
    private boolean mHaveSentUserToCmf = false;
    private int mIcon = R.drawable.ic_drawer_mypebble;
    private boolean mIsEnableNotificationDialogShowing = false;
    private boolean mIsResumed = false;
    private boolean mIsTutorialRunning = false;
    private int mMyPebbleCommitId = -1;
    private boolean mNaggedUserToEnableBt = false;
    private LayoutParams mOverlayLayoutParams = null;
    private TutorialOverlayView mOverlayView = null;
    private OnSharedPreferenceChangeListener mPreferenceChangeListener = new OnSharedPreferenceChangeListener() {
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
            if (key.equals(new PblPreferences(MainActivity.this).prefKeyToString(PrefKey.DEVELOPER_CONNECTION))) {
                MainActivity.this.updateForDeveloperPreferenceChange();
            }
        }
    };
    private Fragment mPreviousFragment;
    private boolean mSwitchedFragmentDuringResume = false;
    private String mTitle = null;
    private TutorialState mTutorialState = null;
    private String mWebviewCustomTitle;
    private ReentrantLock runPrfLock = new ReentrantLock();

    static /* synthetic */ class AnonymousClass9 {
        static final /* synthetic */ int[] $SwitchMap$com$getpebble$android$main$activity$MainActivity$TutorialState = new int[TutorialState.values().length];
        static final /* synthetic */ int[] $SwitchMap$com$getpebble$android$main$fragment$FragmentMetaData$FragmentType = new int[FragmentType.values().length];

        static {
            try {
                $SwitchMap$com$getpebble$android$main$activity$MainActivity$TutorialState[TutorialState.NAV_MENU.ordinal()] = 1;
            } catch (NoSuchFieldError e) {
            }
            try {
                $SwitchMap$com$getpebble$android$main$activity$MainActivity$TutorialState[TutorialState.DISCOVER_APP_STORE.ordinal()] = 2;
            } catch (NoSuchFieldError e2) {
            }
            try {
                $SwitchMap$com$getpebble$android$main$activity$MainActivity$TutorialState[TutorialState.NOTIFICATIONS.ordinal()] = 3;
            } catch (NoSuchFieldError e3) {
            }
            try {
                $SwitchMap$com$getpebble$android$main$activity$MainActivity$TutorialState[TutorialState.APP_LOCKER.ordinal()] = 4;
            } catch (NoSuchFieldError e4) {
            }
            try {
                $SwitchMap$com$getpebble$android$main$activity$MainActivity$TutorialState[TutorialState.GALLERY.ordinal()] = 5;
            } catch (NoSuchFieldError e5) {
            }
            try {
                $SwitchMap$com$getpebble$android$main$fragment$FragmentMetaData$FragmentType[FragmentType.DEVELOPER.ordinal()] = 1;
            } catch (NoSuchFieldError e6) {
            }
            try {
                $SwitchMap$com$getpebble$android$main$fragment$FragmentMetaData$FragmentType[FragmentType.SETTINGS.ordinal()] = 2;
            } catch (NoSuchFieldError e7) {
            }
            try {
                $SwitchMap$com$getpebble$android$main$fragment$FragmentMetaData$FragmentType[FragmentType.SUPPORT.ordinal()] = 3;
            } catch (NoSuchFieldError e8) {
            }
        }
    }

    private class TutorialOverlayView extends View {
        private final float CIRCLE_RADIUS = getDipAsPx(3);
        private final PorterDuffXfermode MODE_CLEAR = new PorterDuffXfermode(Mode.CLEAR);
        private final float NEG_PADDING_1 = getDipAsPx(-1);
        private final float RECT_RADIUS = getDipAsPx(10);
        private final float STROKE_WIDTH = getDipAsPx(2);
        private float mActionBarHeightPx;
        private RectF mCutoutRect = null;
        private final Paint mPaint = new Paint();
        private String mText = null;
        private StaticLayout mTextLayout = null;
        private final TextPaint mTextPaint = new TextPaint();
        private RectF mTextRect = new RectF();

        public TutorialOverlayView(Context context, Typeface typeface) {
            super(context);
            setBackgroundColor(0);
            this.mTextPaint.setAntiAlias(true);
            this.mTextPaint.setTypeface(typeface);
            this.mTextPaint.setTextSize(getSpAsPx(18));
            this.mTextPaint.setColor(-1);
        }

        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            synchronized (MainActivity.this.mTutorialState) {
                switch (AnonymousClass9.$SwitchMap$com$getpebble$android$main$activity$MainActivity$TutorialState[MainActivity.this.mTutorialState.ordinal()]) {
                    case SMTPMessage.RETURN_FULL /*1*/:
                        drawNavMenuOverlay(canvas);
                        break;
                    case SMTPMessage.RETURN_HDRS /*2*/:
                        drawDiscoverAppStoreOverlay(canvas);
                        break;
                    case ListInfo.INDETERMINATE /*3*/:
                        drawNotificationsOverlay(canvas);
                        break;
                    case SMTPMessage.NOTIFY_DELAY /*4*/:
                        drawAppLockerOverlay(canvas);
                        break;
                    case R.styleable.WalletFragmentStyle_maskedWalletDetailsHeaderTextAppearance /*5*/:
                        drawGalleryOverlay(canvas);
                        break;
                }
            }
        }

        private void drawBG(Canvas canvas) {
            this.mPaint.setColor(-16777216);
            this.mPaint.setAlpha(200);
            this.mPaint.setStyle(Style.FILL);
            canvas.drawRect(0.0f, 0.0f, (float) canvas.getWidth(), (float) canvas.getHeight(), this.mPaint);
        }

        private void drawCutout(Canvas canvas, RectF rect) {
            this.mPaint.setColor(-1);
            this.mPaint.setAlpha(30);
            this.mPaint.setStyle(Style.FILL);
            this.mPaint.setXfermode(this.MODE_CLEAR);
            canvas.drawRoundRect(rect, this.RECT_RADIUS, this.RECT_RADIUS, this.mPaint);
            this.mPaint.setXfermode(null);
            this.mPaint.setStyle(Style.STROKE);
            this.mPaint.setStrokeWidth(this.STROKE_WIDTH);
            this.mPaint.setAlpha(200);
            canvas.drawRoundRect(rect, this.RECT_RADIUS, this.RECT_RADIUS, this.mPaint);
        }

        private RectF getRectForResource(int resourceId) {
            return getRectForView(MainActivity.this.findViewById(resourceId));
        }

        private RectF getRectForView(View v) {
            int[] origin = new int[2];
            if (v == null) {
                return null;
            }
            v.getLocationInWindow(origin);
            float left = (float) origin[0];
            float top = (float) origin[1];
            return new RectF(left, top, left + ((float) v.getMeasuredWidth()), top + ((float) v.getMeasuredHeight()));
        }

        private void drawText(Canvas canvas, int textResId, float x, float y, Align align, int dipPadding) {
            float padding = getDipAsPx(dipPadding);
            this.mText = MainActivity.this.getString(textResId);
            this.mTextPaint.setTextAlign(align);
            this.mTextPaint.setFakeBoldText(true);
            this.mTextLayout = new StaticLayout(this.mText, this.mTextPaint, canvas.getWidth(), Alignment.ALIGN_NORMAL, 1.0f, 0.0f, true);
            canvas.save();
            canvas.translate(x, y);
            this.mTextLayout.draw(canvas);
            canvas.restore();
            this.mTextRect.top = y;
            this.mTextRect.bottom = (((float) this.mTextLayout.getHeight()) + y) + padding;
            this.mTextRect.left = this.mTextLayout.getLineLeft(0) - padding;
            this.mTextRect.right = this.mTextLayout.getLineRight(0) - padding;
        }

        private void drawNavMenuOverlay(Canvas canvas) {
            drawBG(canvas);
            if (this.mCutoutRect == null) {
                this.mCutoutRect = new RectF();
            }
            this.mCutoutRect.left = 0.0f;
            this.mCutoutRect.top = 0.0f;
            if (this.mActionBarHeightPx == 0.0f) {
                ActionBar ab = MainActivity.this.getActionBar();
                if (ab != null) {
                    this.mActionBarHeightPx = (float) ab.getHeight();
                }
            }
            this.mCutoutRect.bottom = this.mCutoutRect.top + this.mActionBarHeightPx;
            this.mCutoutRect.right = this.mCutoutRect.bottom;
            RectF rectF = this.mCutoutRect;
            rectF.top -= this.NEG_PADDING_1;
            rectF = this.mCutoutRect;
            rectF.bottom += this.NEG_PADDING_1;
            rectF = this.mCutoutRect;
            rectF.left -= this.NEG_PADDING_1;
            rectF = this.mCutoutRect;
            rectF.right += this.NEG_PADDING_1;
            drawCutout(canvas, this.mCutoutRect);
            float centerY = (this.mCutoutRect.top + this.mCutoutRect.bottom) / 2.0f;
            float startX = this.mCutoutRect.right;
            float stopX = startX + getDipAsPx(65);
            drawLine(canvas, startX, centerY, stopX, centerY);
            this.mPaint.setColor(-1);
            this.mPaint.setAlpha(200);
            this.mPaint.setStyle(Style.FILL);
            canvas.drawCircle(stopX, centerY, this.CIRCLE_RADIUS, this.mPaint);
            Canvas canvas2 = canvas;
            drawText(canvas2, R.string.tutorial_nav_drawer, stopX + getDipAsPx(10), getDipAsPx(15), Align.LEFT, 2);
        }

        private void drawDiscoverAppStoreOverlay(Canvas canvas) {
            drawBG(canvas);
            this.mCutoutRect = null;
            this.mCutoutRect = getRectForDrawerItemByString(R.string.drawer_title_watchfaces);
            RectF rectF = this.mCutoutRect;
            rectF.top -= (float) (MainActivity.this.getActionBar().getHeight() / 2);
            rectF = this.mCutoutRect;
            rectF.bottom -= (float) (MainActivity.this.getActionBar().getHeight() / 2);
            rectF = this.mCutoutRect;
            rectF.bottom += this.mCutoutRect.height();
            drawCutout(canvas, this.mCutoutRect);
            float centerX = (float) (canvas.getWidth() / 2);
            float textTop = this.mCutoutRect.bottom + getDipAsPx(100);
            drawText(canvas, R.string.tutorial_app_store, centerX, textTop, Align.CENTER, 2);
            float stopY = textTop - this.CIRCLE_RADIUS;
            drawLine(canvas, centerX, this.mCutoutRect.bottom, centerX, stopY);
            canvas.drawCircle(centerX, stopY, this.CIRCLE_RADIUS, this.mPaint);
        }

        private void drawNotificationsOverlay(Canvas canvas) {
            drawBG(canvas);
            this.mCutoutRect = getRectForDrawerItemByString(R.string.drawer_title_notifications);
            if (this.mCutoutRect != null) {
                RectF rectF = this.mCutoutRect;
                rectF.top -= (float) (MainActivity.this.getActionBar().getHeight() / 2);
                rectF = this.mCutoutRect;
                rectF.bottom -= (float) (MainActivity.this.getActionBar().getHeight() / 2);
                drawCutout(canvas, this.mCutoutRect);
                float centerX = (float) (canvas.getWidth() / 2);
                float textTop = this.mCutoutRect.bottom + getDipAsPx(100);
                drawText(canvas, R.string.tutorial_notifications, centerX, textTop, Align.CENTER, 10);
                float stopY = textTop - this.CIRCLE_RADIUS;
                drawLine(canvas, centerX, this.mCutoutRect.bottom, centerX, stopY);
                canvas.drawCircle(centerX, stopY, this.CIRCLE_RADIUS, this.mPaint);
            }
        }

        private void drawAppLockerOverlay(Canvas canvas) {
            drawBG(canvas);
            this.mCutoutRect = getRectForResource(R.id.locker_container);
            if (this.mCutoutRect != null) {
                RectF rectF = this.mCutoutRect;
                rectF.bottom -= (float) MainActivity.this.getActionBar().getHeight();
                drawCutout(canvas, this.mCutoutRect);
                float centerX = (float) (canvas.getWidth() / 2);
                drawText(canvas, R.string.tutorial_app_locker, centerX, this.mCutoutRect.top / 3.0f, Align.CENTER, 10);
                float startY = this.mTextRect.bottom + this.CIRCLE_RADIUS;
                drawLine(canvas, centerX, startY, centerX, this.mCutoutRect.top);
                canvas.drawCircle(centerX, startY, this.CIRCLE_RADIUS, this.mPaint);
            }
        }

        private void drawGalleryOverlay(Canvas canvas) {
            drawBG(canvas);
            this.mCutoutRect = getRectForResource(R.id.loaded_watchapps_container);
            if (this.mCutoutRect != null) {
                RectF rectF = this.mCutoutRect;
                rectF.bottom -= (float) MainActivity.this.getActionBar().getHeight();
                drawCutout(canvas, this.mCutoutRect);
                float centerX = (float) (canvas.getWidth() / 2);
                float textTop = this.mCutoutRect.bottom + getDipAsPx(100);
                drawText(canvas, R.string.tutorial_carousel, centerX, textTop, Align.CENTER, 10);
                float stopY = textTop - this.CIRCLE_RADIUS;
                drawLine(canvas, centerX, this.mCutoutRect.bottom, centerX, stopY);
                canvas.drawCircle(centerX, stopY, this.CIRCLE_RADIUS, this.mPaint);
            }
        }

        public void drawLine(Canvas canvas, float startX, float startY, float stopX, float stopY) {
            this.mPaint.setColor(-1);
            this.mPaint.setAlpha(200);
            this.mPaint.setStyle(Style.FILL);
            canvas.drawLine(startX, startY, stopX, stopY, this.mPaint);
        }

        private RectF getRectForDrawerItemByString(int stringId) {
            ListView drawerItems = (ListView) MainActivity.this.findViewById(R.id.lv_main_list);
            if (!(drawerItems == null || MainActivity.this.mDrawerFragment == null)) {
                for (int index = 0; index < 4; index++) {
                    FragmentData fragmentData = FragmentMetaData.getFragmentDataForDrawer(index);
                    if (fragmentData != null && MainActivity.this.getString(fragmentData.getActionBarTitle()).equals(MainActivity.this.getString(stringId))) {
                        return getRectForView(drawerItems.getChildAt(index));
                    }
                }
            }
            return null;
        }

        private float getDipAsPx(int dp) {
            return TypedValue.applyDimension(1, (float) dp, getResources().getDisplayMetrics());
        }

        private float getSpAsPx(int sp) {
            return TypedValue.applyDimension(2, (float) sp, getResources().getDisplayMetrics());
        }
    }

    private enum TutorialState {
        NAV_MENU,
        DISCOVER_APP_STORE,
        NOTIFICATIONS,
        APP_LOCKER,
        GALLERY
    }

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        bindToFrameworkService();
        setContentView(R.layout.activity_main);
        findViewById(R.id.connection_manager_container).setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                MobileAppBehavior.logDisconnectedDrawerItemTapped();
                MainActivity.this.switchFragmentByType(FragmentType.CONNECTION_MANAGER);
                MainActivity.this.closeDrawer();
            }
        });
        this.mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        initDrawerLayout();
        this.mDrawerFragment = (DrawerFragment) getFragmentManager().findFragmentById(R.id.navigation_drawer);
        updateDeveloperFragmentState();
        getFragmentManager().addOnBackStackChangedListener(new OnBackStackChangedListener() {
            public void onBackStackChanged() {
                if (MainActivity.this.getCurrentFragment() == null) {
                    Trace.debug(MainActivity.this.TAG, "Current fragment: " + null + ", allow null stack: " + MainActivity.this.mAllowNullStack);
                    if (!MainActivity.this.mAllowNullStack) {
                        MainActivity.this.finish();
                        return;
                    }
                    return;
                }
                MainActivity.this.mPreviousFragment = MainActivity.this.getCurrentFragment();
                MainActivity.this.updateStyleForFragment(MainActivity.this.mPreviousFragment);
                MainActivity.this.setTapToConnectVisibility();
                MainActivity.this.updateActionBarForCurrentFragment();
            }
        });
        if (getCurrentFragment() == null) {
            this.mTitle = getTitle().toString();
            setActionBarIcon(this.mIcon);
        } else {
            updateActionBarForCurrentFragment();
        }
        PebbleApplication.addConnectedDeviceChangeListener(this.mConnectedDeviceChangeListener);
    }

    private void updateActionBarForCurrentFragment() {
        if (getCurrentFragment() != null) {
            FragmentType fragmentType = FragmentMetaData.getFragmentType(getCurrentFragment());
            Trace.debug(this.TAG, "Current fragment: " + getCurrentFragment().getClass());
            if (fragmentType != null) {
                updateActionBarForFragment(FragmentMetaData.getFragmentDataByType(fragmentType));
            }
        }
    }

    protected void bindToFrameworkService() {
        PebbleApplication.bindToFrameworkService();
    }

    private void updateStyleForFragment(Fragment previousFragment) {
        if (previousFragment == null) {
            Trace.error(this.TAG, "previousFragment was null");
            return;
        }
        FragmentType fragmentType = FragmentMetaData.getFragmentType(previousFragment);
        FragmentData fragmentData = FragmentMetaData.getFragmentDataByType(fragmentType);
        Trace.debug(this.TAG, "Current fragment: " + getCurrentFragment().getClass());
        if (fragmentType == null || fragmentData == null) {
            Trace.error(this.TAG, "Could not retrieve style for fragment, using AppTheme");
            return;
        }
        updateActionBarForFragment(fragmentData);
        updateStatusbarForFragment(fragmentData);
    }

    private void updateStatusbarForFragment(FragmentData fragmentData) {
        if (fragmentData == null) {
            Trace.error(this.TAG, "Failed to set statusbar color: fragment data was null");
        } else if (VERSION.SDK_INT >= 21) {
            Window window = getWindow();
            if (window != null) {
                window.setStatusBarColor(getResources().getColor(fragmentData.getStatusBarColor()));
            }
        }
    }

    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
    }

    private void handleIntent(Intent intent) {
        DeepLink deepLink = new DeepLink(intent, getApplicationContext());
        this.mForceSkipOnboarding = deepLink.forceSkipOnboarding();
        Sideloading sideloadingLink = new Sideloading(this, intent);
        if (deepLink.isDeepLink()) {
            try {
                handleDeepLink(deepLink);
            } catch (Exception e) {
                Trace.error(this.TAG, "Failed to handle deep link.", e);
            }
        } else if (sideloadingLink.isValidSideloadingIntent()) {
            try {
                handleSideloadingIntent(sideloadingLink);
            } catch (Exception e2) {
                Trace.error(this.TAG, "Failed to handle sideloading intent.", e2);
            }
        }
        if (intent != null && intent.getBooleanExtra("show_cmf", false)) {
            this.mHaveSentUserToCmf = false;
        }
    }

    private void handleDeepLink(DeepLink deepLink) {
        if (deepLink.needsFragmentSwitch()) {
            FragmentType newFragmentType = deepLink.getFragmentTypeToSwitch();
            if (newFragmentType != null) {
                setIntent(null);
                Trace.debug(this.TAG, "handleDeepLink: switching fragment");
                switchFragmentByType(newFragmentType, deepLink.getFragmentArgs());
                this.mSwitchedFragmentDuringResume = true;
                return;
            }
            Trace.error(this.TAG, "DeepLink needs fragment switch, but no fragment type found.");
        } else if (deepLink.isDeepLink()) {
            deepLink.handleLink();
        }
    }

    private void handleSideloadingIntent(Sideloading sideloadingLink) {
        FragmentType newFragmentType = sideloadingLink.getFragmentTypeToSwitch();
        if (newFragmentType != null) {
            setIntent(null);
            Trace.debug(this.TAG, "handleSideloadingIntent: switching fragment");
            switchFragmentByType(newFragmentType, sideloadingLink.getFragmentArgs());
            this.mSwitchedFragmentDuringResume = true;
            return;
        }
        Trace.error(this.TAG, "Sideloading needs fragment switch, but no fragment type found.");
    }

    private void switchFragmentByType(FragmentType fragmentType) {
        switchFragmentByType(fragmentType, null);
    }

    public void onDestroy() {
        super.onDestroy();
        sHandler.removeCallbacks(null);
        PebbleApplication.removeConnectedDeviceChangeListener(this.mConnectedDeviceChangeListener);
    }

    public void switchFragmentByType(FragmentType fragmentType, Bundle fragmentArgs) {
        FragmentData fragmentData = FragmentMetaData.getFragmentDataByType(fragmentType);
        if (fragmentData == null) {
            Trace.error(this.TAG, "No fragment data!");
        } else if (isFinishing() || isActivityDestroyed()) {
            Trace.info(this.TAG, "Activity destroyed; not switching fragment");
        } else {
            this.mWebviewCustomTitle = null;
            if (fragmentData.needsInternetConnection() && !HttpUtils.hasInternetConnection(this)) {
                Trace.info(this.TAG, "Fragment: " + fragmentType + " requested, but needs internet connection which is not available...");
                fragmentType = FragmentType.NO_NETWORK_CONNECTION;
                fragmentData = FragmentMetaData.getFragmentDataByType(fragmentType);
                if (fragmentData == null) {
                    Trace.error(this.TAG, "No fragment data! (NO_NETWORK_CONNECTION)");
                    return;
                }
            }
            Fragment fragment = fragmentData.createFragment(fragmentArgs);
            boolean force = false;
            int popFlag = 0;
            if (isMyPebbleFragment(fragmentType)) {
                popFlag = 1;
                this.mAllowNullStack = true;
            }
            if (this.mMyPebbleCommitId >= 0) {
                getFragmentManager().popBackStack(this.mMyPebbleCommitId, popFlag);
            }
            if (isMyPebbleFragment(fragmentType)) {
                if (this.mMyPebbleCommitId >= 0) {
                    force = true;
                }
                int commitId = switchFragment(fragment, true, force, true);
                this.mAllowNullStack = false;
                if (commitId >= 0) {
                    this.mMyPebbleCommitId = commitId;
                    return;
                }
                return;
            }
            switchFragment(fragment, true, false, true);
        }
    }

    private boolean isMyPebbleFragment(FragmentType fragmentType) {
        return fragmentType.equals(FragmentType.MY_PEBBLE);
    }

    private void updateActionBarForFragment(FragmentData fragmentData) {
        this.mTitle = getResources().getString(fragmentData.getActionBarTitle());
        this.mIcon = fragmentData.getActionBarIcon();
        this.mActionBarColorId = fragmentData.getActionBarColor();
        restoreActionBar();
    }

    private void initDrawerLayout() {
        if (this.mDrawerLayout != null) {
            this.mDrawerLayout.setDrawerShadow((int) R.drawable.drawer_shadow, 8388611);
            ActionBar actionBar = getActionBar();
            if (actionBar != null) {
                actionBar.setDisplayHomeAsUpEnabled(true);
                actionBar.setHomeButtonEnabled(true);
            }
            this.mDrawerLayout.setDrawerShadow((int) R.drawable.drawer_shadow, 3);
            this.mDrawerToggle = new ActionBarDrawerToggle(this, this.mDrawerLayout, R.drawable.ic_navigation_drawer, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
                public void onDrawerClosed(View drawerView) {
                    super.onDrawerClosed(drawerView);
                    MainActivity.this.invalidateOptionsMenu();
                }

                public void onDrawerOpened(View drawerView) {
                    if (MainActivity.this.mIsTutorialRunning) {
                        MainActivity.this.mTutorialState = TutorialState.DISCOVER_APP_STORE;
                        MainActivity.this.mOverlayView.invalidate();
                    }
                    super.onDrawerOpened(drawerView);
                    MainActivity.this.invalidateOptionsMenu();
                }
            };
            this.mDrawerToggle.syncState();
            this.mDrawerLayout.setDrawerListener(this.mDrawerToggle);
        }
    }

    public void onStart() {
        super.onStart();
        PebbleApplication.onActivityOnStart();
        updateDrawerFragmentItems();
    }

    public void onStop() {
        super.onStop();
        PebbleApplication.onActivityOnStop();
    }

    public void updateForDeveloperPreferenceChange() {
        updateDeveloperFragmentState();
        updateDrawerFragmentItems();
    }

    private void updateDeveloperFragmentState() {
        if (new PblPreferences(this).getBooleanData(PrefKey.DEVELOPER_CONNECTION, false)) {
            FragmentMetaData.addDeveloperToDrawer();
        } else {
            FragmentMetaData.removeDeveloperFromDrawer();
        }
    }

    private void updateDrawerFragmentItems() {
        if (this.mDrawerFragment != null) {
            int index;
            FragmentData fragmentData;
            this.mDrawerFragment.setOnItemClickListener(this);
            this.mDrawerFragment.clearMenuItems();
            for (index = 0; index < 4; index++) {
                fragmentData = FragmentMetaData.getFragmentDataForDrawer(index);
                if (fragmentData != null) {
                    this.mDrawerFragment.addMainMenuItem(new DrawerItem(getString(fragmentData.getActionBarTitle()), fragmentData.getActionBarIcon()));
                }
            }
            for (index = 4; index < FragmentMetaData.getDrawerCount(); index++) {
                fragmentData = FragmentMetaData.getFragmentDataForDrawer(index);
                this.mDrawerFragment.addSubMenuItem(new DrawerItem(getString(fragmentData.getActionBarTitle()), fragmentData.getActionBarIcon()));
            }
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        switch (requestCode) {
            case SMTPMessage.RETURN_FULL /*1*/:
                handleResume();
                return;
            case SMTPMessage.RETURN_HDRS /*2*/:
                switchFragmentByType(FragmentType.MY_PEBBLE);
                return;
            default:
                return;
        }
    }

    private boolean runLoginIfNeeded() {
        boolean isLoggedin;
        Trace.debug(this.TAG, "runLoginIfNeeded()");
        if (PebbleApplication.getSessionManager().getUserAccount() != null) {
            isLoggedin = true;
        } else {
            isLoggedin = false;
        }
        if (isLoggedin) {
            Trace.debug(this.TAG, "Login not needed");
            return false;
        }
        Trace.debug(this.TAG, "User account was null; login is needed");
        Intent intent = new Intent(this, LoginActivity.class);
        intent.addFlags(268500992);
        startActivity(intent);
        finish();
        return true;
    }

    public void onPostResume() {
        Trace.debug(this.TAG, "onPostResume()");
        super.onPostResume();
        this.mSwitchedFragmentDuringResume = false;
        PblFrameworkInterface frameworkInterface = PebbleApplication.getFrameworkInterface();
        if (frameworkInterface != null) {
            frameworkInterface.requestConnectionStateProcessing();
        } else {
            Trace.warning(this.TAG, "onPostResume() frameworkInterface is null");
        }
        SyncBootConfig.syncBootConfigIfRequired(null, getApplicationContext(), null, false);
        updateStyleForFragment(this.mPreviousFragment);
        Intent intent = getIntent();
        if (intent != null) {
            handleIntent(intent);
        }
        if (runLoginIfNeeded()) {
            Trace.debug(this.TAG, "Running login");
            return;
        }
        new PblPreferences(this).registerOnSharedPreferenceChangeListener(this.mPreferenceChangeListener);
        if (runOnboardingIfNeeded()) {
            Trace.debug(this.TAG, "Running Onboarding");
        } else if (runTutorialIfNeeded()) {
            Trace.debug(this.TAG, "Running Tutorial");
        } else {
            this.mIsResumed = true;
            handleResume();
        }
    }

    public boolean dispatchTouchEvent(MotionEvent event) {
        if (!this.mIsTutorialRunning || event.getAction() != 0) {
            return super.dispatchTouchEvent(event);
        }
        goToNextStep();
        return true;
    }

    private boolean runOnboardingIfNeeded() {
        if (!needsOnboarding()) {
            return false;
        }
        sHandler.post(new Runnable() {
            public void run() {
                MainActivity.this.startActivityForResult(new Intent(MainActivity.this, OnboardingActivity.class), 2);
                MainActivity.this.finish();
            }
        });
        return true;
    }

    public boolean isTutorialRunning() {
        return this.mIsTutorialRunning;
    }

    private boolean runTutorialIfNeeded() {
        if (this.mIsTutorialRunning) {
            Trace.debug(this.TAG, "Tutorial is already running");
            return false;
        }
        PblPreferences pblPreferences = new PblPreferences(this);
        if (pblPreferences == null) {
            Trace.error(this.TAG, "PblPreferences were null");
            return false;
        }
        if (!(this.mSwitchedFragmentDuringResume || pblPreferences.getBooleanData(PrefKey.TUTORIAL_COMPLETED, false))) {
            switchFragmentByType(FragmentType.MY_PEBBLE);
            showTutorialOverlay();
            this.mIsTutorialRunning = true;
        }
        return this.mIsTutorialRunning;
    }

    public boolean needsOnboarding() {
        if (this.mForceSkipOnboarding) {
            return false;
        }
        return OnboardingActivity.isOnboardingRequired();
    }

    private void handleResume() {
        if (BluetoothUtil.isBluetoothEnabled() || this.mNaggedUserToEnableBt) {
            PblPreferences prefs = new PblPreferences(this);
            if (PebbleApplication.getLastConnectedDeviceRecord() == null && !prefs.getBooleanData(PrefKey.USER_SEEN_PEBBLE_ONLY_SCREEN, false)) {
                switchFragment(new PebbleOnlyFragment());
                return;
            } else if (ensurePebbleConnected() || this.mHaveSentUserToCmf || this.mSwitchedFragmentDuringResume) {
                if (!this.mSwitchedFragmentDuringResume && getCurrentFragment() == null) {
                    switchFragmentByType(FragmentType.MY_PEBBLE);
                }
                PblPreferences pblPreferences = new PblPreferences(getApplicationContext());
                boolean naggedToEnableNotificaitonListener = false;
                if (pblPreferences != null) {
                    naggedToEnableNotificaitonListener = pblPreferences.getBooleanData(PrefKey.NAGGED_ABOUT_ENABLING_NOTIFICATION_LISTENER, false);
                }
                if (!this.mIsEnableNotificationDialogShowing && !NotificationUtil.isServiceEnabled(this) && !naggedToEnableNotificaitonListener) {
                    showEnableNotificationListenerDialog();
                    return;
                }
                return;
            } else {
                this.mHaveSentUserToCmf = true;
                switchFragmentByType(FragmentType.CONNECTION_MANAGER);
                return;
            }
        }
        this.mNaggedUserToEnableBt = true;
        startActivityForResult(new Intent("android.bluetooth.adapter.action.REQUEST_ENABLE"), 1);
    }

    private void showEnableNotificationListenerDialog() {
        this.mIsEnableNotificationDialogShowing = true;
        final PblPreferences pblPreferences = new PblPreferences(getApplicationContext());
        new Builder(this).setTitle(getString(R.string.enable_notifications_dialog_title)).setMessage(getString(R.string.enable_notifications_dialog_text)).setPositiveButton(getString(R.string.enable_notifications_service_dialog_btn_positive), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface arg0, int arg1) {
                pblPreferences.setBooleanData(PrefKey.NAGGED_ABOUT_ENABLING_NOTIFICATION_LISTENER, true);
                NotificationUtil.showEnableServiceActivity(MainActivity.this);
                MainActivity.this.mIsEnableNotificationDialogShowing = false;
            }
        }).setNegativeButton(getResources().getString(R.string.enable_notifications_service_dialog_btn_negative), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface arg0, int arg1) {
                MainActivity.this.mIsEnableNotificationDialogShowing = false;
            }
        }).setCancelable(false).show();
    }

    private boolean ensurePebbleConnected() {
        return PebbleApplication.getConnectedDevice() != null;
    }

    public void onPause() {
        this.mIsResumed = false;
        super.onPause();
        new PblPreferences(this).unregisterOnSharedPreferenceChangeListener(this.mPreferenceChangeListener);
    }

    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
        Trace.debug(this.TAG, "onItemClick()");
        FragmentData fragmentData = FragmentMetaData.getFragmentDataForDrawer(position);
        logAnalyticsForDrawerClick(fragmentData);
        Fragment currentFragment = getCurrentFragment();
        FragmentType currentFragmentType = currentFragment != null ? FragmentMetaData.getFragmentType(currentFragment) : null;
        boolean sameType = currentFragmentType != null && currentFragmentType.equals(fragmentData.getType());
        if (fragmentData != null && ((currentFragment == null || !sameType) && !(currentFragmentType == FragmentType.CONNECTION_MANAGER && runOnboardingIfNeeded()))) {
            switchFragmentByType(fragmentData.getType());
            setDrawerIndicatorEnabled(true);
        }
        closeDrawer();
    }

    private void logAnalyticsForDrawerClick(FragmentData fragmentData) {
        switch (AnonymousClass9.$SwitchMap$com$getpebble$android$main$fragment$FragmentMetaData$FragmentType[fragmentData.getType().ordinal()]) {
            case SMTPMessage.RETURN_FULL /*1*/:
                MobileAppBehavior.logDeveloperDrawerItemTapped();
                return;
            case SMTPMessage.RETURN_HDRS /*2*/:
                MobileAppBehavior.logSettingsDrawerItemTappedEvent();
                return;
            case ListInfo.INDETERMINATE /*3*/:
                Support.logSupportDrawerItemTapped();
                return;
            default:
                return;
        }
    }

    private void openDrawer() {
        if (this.mDrawerLayout != null) {
            this.mDrawerLayout.openDrawer(8388611);
        }
    }

    private void closeDrawer() {
        if (this.mDrawerLayout != null) {
            this.mDrawerLayout.closeDrawer(8388611);
        }
    }

    public void restoreActionBar() {
        ActionBar actionBar = getActionBar();
        if (actionBar != null) {
            actionBar.setNavigationMode(0);
            actionBar.setDisplayShowTitleEnabled(true);
            actionBar.setTitle(this.mWebviewCustomTitle != null ? this.mWebviewCustomTitle : this.mTitle);
            actionBar.setIcon(this.mIcon);
            actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(this.mActionBarColorId)));
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
    }

    public void setWebviewCustomTitle(String title) {
        this.mWebviewCustomTitle = title;
        restoreActionBar();
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        if (this.mDrawerToggle.isDrawerIndicatorEnabled() && this.mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        switch (item.getItemId()) {
            case 16908332:
                onBackPressed();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    public void setDrawerIndicatorEnabled(boolean enable) {
        this.mDrawerToggle.setDrawerIndicatorEnabled(enable);
    }

    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        this.mDrawerToggle.onConfigurationChanged(newConfig);
    }

    private void showTutorialOverlay() {
        this.mOverlayLayoutParams = new LayoutParams();
        this.mOverlayLayoutParams.type = 2;
        this.mOverlayLayoutParams.gravity = 51;
        this.mOverlayLayoutParams.height = -1;
        this.mOverlayLayoutParams.width = -1;
        this.mOverlayLayoutParams.flags = 24;
        this.mOverlayLayoutParams.format = -2;
        this.mTutorialState = TutorialState.NAV_MENU;
        if (this.mOverlayView == null) {
            this.mOverlayView = new TutorialOverlayView(this, PblFont.getFontLight(this));
        }
        ((WindowManager) getSystemService("window")).addView(this.mOverlayView, this.mOverlayLayoutParams);
    }

    private void finishTutorial() {
        this.mIsTutorialRunning = false;
        new PblPreferences(this).setBooleanData(PrefKey.TUTORIAL_COMPLETED, true);
        ((WindowManager) getSystemService("window")).removeView(this.mOverlayView);
        handleResume();
    }

    private void goToNextStep() {
        synchronized (this.mTutorialState) {
            switch (AnonymousClass9.$SwitchMap$com$getpebble$android$main$activity$MainActivity$TutorialState[this.mTutorialState.ordinal()]) {
                case SMTPMessage.RETURN_FULL /*1*/:
                    openDrawer();
                    break;
                case SMTPMessage.RETURN_HDRS /*2*/:
                    this.mTutorialState = TutorialState.NOTIFICATIONS;
                    break;
                case ListInfo.INDETERMINATE /*3*/:
                    closeDrawer();
                    this.mTutorialState = TutorialState.APP_LOCKER;
                    break;
                case SMTPMessage.NOTIFY_DELAY /*4*/:
                    this.mTutorialState = TutorialState.GALLERY;
                    break;
                case R.styleable.WalletFragmentStyle_maskedWalletDetailsHeaderTextAppearance /*5*/:
                    this.mIsTutorialRunning = false;
                    finishTutorial();
                    break;
            }
            this.mOverlayView.invalidate();
        }
    }
}
